import React, { useEffect, useState } from 'react';
import {
  Row,
  Col,
  Card,
  Statistic,
  Typography,
  Spin,
  Tag,
  Popover,
  Alert,
  Carousel,
  Input,
  Tooltip as AntdToolTip,
} from 'antd';

import { InfoCircleOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar,
} from 'recharts';
import TagWall from '../../components/TagWall';
import Notification from '../../components/Notification';
import CustomCarousel from '../../components/CustomCarousel';
import './Home.css';
import LingyaImg from '../../images/lingya.png';
import YuyuantanImg from '../../images/玉渊潭.jpg';
import ChatGptImg from '../../images/chatGPT.jpg';

const { Title, Text } = Typography;
const AuthorTips = () => {
  const customStyle = {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'flex-start',
    width: '100%',
    padding: '10px 20px',
    backgroundColor: '#E0F2FF',
    borderRadius: '8px',
    boxShadow: '0px 4px 6px rgba(0, 0, 0, 0.1)',
    marginTop: '20px',
  };

  const titleStyle = {
    fontSize: '16px',
    fontWeight: 'bold',
    marginRight: '10px',
  };

  return (
    <div style={customStyle}>
      <span style={titleStyle}>作者tips:</span>
      <br />
      <span>
        熬夜写代码容易失眠
        <br />
        我知道主页这样很丑，之后会魔改
      </span>
    </div>
  );
};
const updateDescription = (
  <>
    <ol>
      <li>当前版本：0.2.1</li>
      <li>
        <span color='red'>阅读管理模块-(书籍详情页)</span>终于上线了
      </li>
      <li>新工具-题库</li>
    </ol>
    <AuthorTips />
  </>
);
const Home = () => {
  const [userInfo, setUserInfo] = useState(null);
  const [infoLoading, setInfoLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [headPicture, setHeadPicture] = useState(
    localStorage.getItem('headSculptureUrl') ||
      'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png'
  );
  const content = (
    <div>
      <p>目前下方面板的数据为mock数据，真实数据待开发中</p>
      <p>
        网站建立初期可免费申请vip，联系小博就可以了
        <span style={{ fontSize: '14px', color: 'green' }}>
          (其实也没什么差别)
        </span>
      </p>
      <p>
        目前开发的功能有，登录注册，阅读管理，markdown编辑器的导出
        <span style={{ fontSize: '14px', color: 'red' }}>(暂不支持图片)</span>
        ，小工具
        <span style={{ fontSize: '14px', color: 'red' }}>
          (加密解密，ivySCI笔记导入导出)
        </span>
      </p>
    </div>
  );
  const getUserInfo = () => {
    const token = sessionStorage.getItem('token');
    console.log('token:', token);
    const url = `http://localhost:29157/api/users/userInfo?token=${token}`;
    console.log('url:', url);
    fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    })
      .then(response => response.json())
      .then(data => {
        const {
          email,
          identity,
          nickname,
          signature,
          username,
          headSculptureUrl,
        } = data.data;
        setUserInfo(data.data);
        // 将各个字段存储到localStorage中
        localStorage.setItem('email', email);
        localStorage.setItem('identity', identity);
        localStorage.setItem('nickname', nickname);
        localStorage.setItem('signature', signature);
        localStorage.setItem('username', username);
        if (localStorage.getItem('headSclptureUrl') === undefined)
          localStorage.setItem('headSculptureUrl', headSculptureUrl);
      })
      .catch(error => {
        console.error(error);
      })
      .finally(setInfoLoading(true));
  };
  useEffect(() => {
    getUserInfo();
  }, []);

  useEffect(() => {
    console.log('userInfo:', userInfo);
  }, [userInfo]);
  const data = [
    { month: 'Jan', count: 12 },
    { month: 'Feb', count: 23 },
    { month: 'Mar', count: 34 },
    { month: 'Apr', count: 45 },
    { month: 'May', count: 56 },
    { month: 'Jun', count: 67 },
    { month: 'Jul', count: 78 },
    { month: 'Aug', count: 89 },
    { month: 'Sep', count: 100 },
    { month: 'Oct', count: 111 },
    { month: 'Nov', count: 122 },
    { month: 'Dec', count: 133 },
  ];

  const data2 = [
    { type: '小说', count: 36 },
    { type: '传记', count: 52 },
    { type: '历史', count: 68 },
    { type: '科技', count: 94 },
    { type: '艺术', count: 63 },
    { type: '哲学', count: 49 },
    { type: '经济', count: 75 },
    { type: '政治', count: 81 },
  ];
  const data3 = [
    '羽毛球',
    '做饭',
    '桌游',
    '剧本杀',
    '密室',
    'python',
    'react',
    'java',
    'mysql',
    'ssm',
    'springboot',
    '炒股',
    '尤克里里',
    '阅读',
    '旅行',
  ];
  const getColor = identity => {
    switch (identity) {
      case '普通用户':
        return 'cyan';
      case 'VIP用户':
        return 'magenta';
      case '系统管理员':
        return 'geekblue';
      case '系统创始人':
        return 'gold';
      default:
        return 'default';
    }
  };
  const carouselItems = [
    {
      title: '铃芽之旅，你去看了吗？',
      image: LingyaImg,
      linkUrl: 'https://example.com/travel',
    },
    {
      title: '好想去玉渊潭玩',
      image: YuyuantanImg,
      linkUrl: 'https://example.com/website',
    },
    {
      title: 'ChatGPT使用经验总结',
      image: ChatGptImg,
      linkUrl: 'https://example.com/chatgpt',
    },
  ];
  return (
    <div>
      {/* 顶部区域 */}
      <div className='top-section'>
        <div className='left-top-section'>
          <div className='avatar-container'>
            <img
              src={headPicture}
              alt='avatar'
            />
          </div>

          {infoLoading && userInfo ? (
            <div className='user-info'>
              <Title level={4}>
                <span style={{ marginRight: '8px' }}>
                  {userInfo.nickname || userInfo.username}
                </span>
                <Tag color={getColor(userInfo.identity)}>
                  {userInfo.identity}
                </Tag>
                <Popover
                  content={content}
                  trigger='hover'
                  visible={visible}
                  onVisibleChange={setVisible}>
                  <QuestionCircleOutlined
                    style={{ color: 'blue', fontSize: '18px' }}
                  />
                </Popover>
              </Title>
              <Text strong>
                {userInfo.signature
                  ? userInfo.signature.split('\\n').map((line, i) => (
                      <React.Fragment key={i}>
                        {line}
                        <br />
                      </React.Fragment>
                    ))
                  : '你还没有写个性签名哦？快去设置中编辑吧~'}
              </Text>
            </div>
          ) : (
            <Spin tip={'加载中请稍后'} />
          )}
        </div>

        <div className='right-top-section'>
          <Statistic
            title='阅读次数'
            value={0}
            valueStyle={{ color: '#1890ff' }}
          />
          &nbsp;&nbsp;
          <Statistic
            title='参加活动'
            value={0}
            valueStyle={{ color: '#f5222d' }}
          />
          &nbsp;&nbsp;
          <Statistic
            title='掌握技能'
            value={0}
            valueStyle={{ color: '#52c41a' }}
          />
        </div>
      </div>
      {/* 中间区域 */}
      <div className='middle-section'>
        <Row>
          <Col span={17}>
            <Notification
              message='更新提示'
              description={updateDescription}
            />
          </Col>
          <Col span={7}>
            <div
              className='carousel-wrapper'
              style={{ marginTop: '20px' }}>
              <CustomCarousel items={carouselItems} />
            </div>
          </Col>
        </Row>
      </div>
      {/* 底部区域 */}
      <div className='bottom-section'>
        <Row>
          <Col span={8}>
            <Card className='chart-card'>
              <div className='chart-title'>
                掌握的技能<p style={{ color: 'red' }}>(模拟数据)</p>
              </div>
              <TagWall tags={data3} />
            </Card>
          </Col>
          <Col span={8}>
            <Card className='chart-card'>
              <div className='chart-title'>
                月度参加活动次数<p style={{ color: 'red' }}>(模拟数据)</p>
              </div>
              <LineChart
                width={400}
                height={200}
                data={data}>
                <CartesianGrid strokeDasharray='3 3' />
                <XAxis dataKey='month' />
                <YAxis />
                <Tooltip />
                <Legend />
                <Line
                  type='monotone'
                  dataKey='count'
                  stroke='#82ca9d'
                  activeDot={{ r: 8 }}
                />
              </LineChart>
            </Card>
          </Col>
          <Col span={8}>
            <Card className='chart-card'>
              <div className='chart-title'>
                阅读书目类型<p style={{ color: 'red' }}>(模拟数据)</p>
              </div>
              <RadarChart
                width={400}
                height={200}
                data={data2}>
                <PolarGrid />
                <PolarAngleAxis dataKey='type' />
                <PolarRadiusAxis
                  angle={30}
                  domain={[0, 100]}
                />
                <Tooltip />
                <Radar
                  name='阅读书目类型'
                  dataKey='count'
                  stroke='#8884d8'
                  fill='#8884d8'
                  fillOpacity={0.6}
                />
              </RadarChart>
            </Card>
          </Col>
        </Row>
      </div>
    </div>
  );
};

export default Home;
